<?php

require_once("xmlparser.php");

class OracleConnection 
{
    private $HOST = "127.0.0.1";
    private $PORT = "4242";
    private $socket = false;

    private function connect()
    {
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ( !($this->socket) ) return false; 
        if ( !(socket_connect($this->socket, $this->HOST, $this->PORT)) ){ $this->socket = false; return false; }
        return true;
    }

    private function disconnect()
    {
        socket_close($this->socket);
        $this->socket = false;
    }

    private function send($msg)
    {
        if ( !($this->socket) ) return false;
      
        $length = strlen($msg);
        while(true) {
            $sent = socket_write($this->socket, $msg, $length);
            if ( !($sent) ) return false;
            if ( $sent >= $length ) return true;
            if ( $sent < $length ) {
                $msg = substr($msg, $sent);
                $length -= $sent;
            }
        }
    }

    private function recv()
    {
		if ( !($this->socket) ) return false;

        $recv = "";        
		$done = false;
        while($done == false) {
			$buff = socket_read($this->socket, 1, PHP_BINARY_READ);
            if ( $buff === FALSE ) break;

	    	if ( $buff == "<" ) { 
				$tag = true; $tagm = "<"; 
			} else if ( $tag && $buff == ">" ) {
				$tagm .= ">";
				$tag = false;
	      		if ( $tagm == "</response>" ) 
					$done = true;
			} else if ( $tag ) {
				$tagm .= $buff;
			} 
            $recv .= $buff;
        }

        return ( $done == false ? false : $recv );
    }
    
    public function query($query) 
    {
        if ( !$this->connect() ) {
			throw new Exception("Can't connect to the oracle!");
		}

        if ( !$this->send($query) ) {
			throw new Exception("The query could not been sent to the oracle!");
		}

        $response = $this->recv();
        if ( !$response ) {
			throw new Exception("The response could not been received from the oracle!");
		}
     
        $this->disconnect();
        return $response;
    }
}

?>
